package site.lanmushan.framework.datascope.interceptor.mysql;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import site.lanmushan.framework.datascope.bean.DataControlUserContext;
import site.lanmushan.framework.datascope.properties.DataScopeRule;
import site.lanmushan.framework.datascope.support.DataScopeConditionProvider;
import site.lanmushan.groovyscript.GroovyScriptUtil;

import java.util.List;

/**
 * @author Administrator
 */
@Slf4j
public class MysqlDataScopeRuleConditionProvider implements DataScopeConditionProvider {


    @Override
    public String getCondition(String tableName, DataControlUserContext context, List<DataScopeRule> list, List<DataScopeRule> global) {
        JSONObject json = (JSONObject) JSONObject.toJSON(context);
        String result = null;
        if (list == null) {
            list = global;
        }
        if (list != null) {
            for (DataScopeRule rule : list) {
                if(StringUtils.isEmpty(rule.getRuleCondition())){
                    continue;
                }
                Boolean success = (Boolean) GroovyScriptUtil.execute(rule.getRuleCondition(), context, json.getInnerMap(), Boolean.class);
                if (success) {
                    String content=JSONObject.toJSONString(rule.getRuleValue());
                    result = (String) GroovyScriptUtil.execute(content, context, json.getInnerMap(), String.class);
                    return result;
                }
            }

        }
        return null;
    }
}
